import axios from 'axios'
import {
  Message
} from 'element-ui'
import store from '../store'
import {
  getToken,
  removeToken
} from '@/utils/auth'

// 创建axios实例
const service = axios.create({
  baseURL: process.env.BASE_API, // api的base_url
  timeout: 50000, // 请求超时时间
  headers: {
    'X-Requested-With': 'XMLHttpRequest',
    'Content-Type': 'application/json'
  }
})

// request拦截器
service.interceptors.request.use(
  config => {
    if (store.getters.token) {
      config.headers['x-access-token'] = getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
    }
    return config
  },
  error => {
    // 对请求错误做些什么
    console.log(error) // for debug
    Promise.reject(error)
  }
)

// respone拦截器
service.interceptors.response.use(
  response => {
    const res = response.data
    let message = '未登录，或登录失效，请登录'
    switch (res.code) {
      case 0: //正常状态
        return res.data
      case 20000: // loginError
        break
      case 20001: //未激活
        message = '该账号已关闭，请联系管理员'
        break
      default:
        break
    }
    store.dispatch('LogOut').then(() => {
      Message.error(message)
      location.reload()
    })
    return Promise.reject('error')
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: "网络异常，请稍后重试",
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
